import React, { useState, useEffect, useMemo } from 'react';
import { useLocation, Link } from 'react-router-dom';
import { createPageUrl } from '@/utils';
import { optimizeWorkPlan } from '@/api/functions';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { ArrowLeft, AlertTriangle, GanttChartSquare, CheckCircle, Info, ListChecks, ThumbsUp, CalendarOff } from 'lucide-react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { format, parseISO, differenceInDays } from 'date-fns';

const CustomTooltip = ({ active, payload, label }) => {
    if (active && payload && payload.length) {
        const data = payload[0].payload;
        return (
            <div className="bg-white p-3 border rounded-lg shadow-lg">
                <p className="font-bold">{data.name}</p>
                <p className="text-sm text-gray-600">项目: {data.projectName}</p>
                <p className="text-sm">开始: {data.startDate}</p>
                <p className="text-sm">结束: {data.endDate}</p>
                <p className="text-sm">工期: {data.durationDays} 天</p>
            </div>
        );
    }
    return null;
};

const TaskList = ({ tasks, title, icon }) => (
    <Card>
        <CardHeader>
            <CardTitle className="flex items-center gap-2">
                {icon}
                {title}
            </CardTitle>
        </CardHeader>
        <CardContent>
            <Table>
                <TableHeader>
                    <TableRow>
                        <TableHead>跨越点名称</TableHead>
                        <TableHead>所属项目</TableHead>
                        <TableHead>施工单位</TableHead>
                        <TableHead>开始日期</TableHead>
                        <TableHead>结束日期</TableHead>
                        <TableHead>工期(天)</TableHead>
                    </TableRow>
                </TableHeader>
                <TableBody>
                    {tasks.map(task => (
                        <TableRow key={task.id}>
                            <TableCell className="font-medium">{task.name}</TableCell>
                            <TableCell>{task.projectName}</TableCell>
                            <TableCell>{task.constructionUnit}</TableCell>
                            <TableCell>{task.startDate ? format(parseISO(task.startDate), 'yyyy-MM-dd') : '-'}</TableCell>
                            <TableCell>{task.endDate ? format(parseISO(task.endDate), 'yyyy-MM-dd') : '-'}</TableCell>
                            <TableCell>{task.durationDays || '-'}</TableCell>
                        </TableRow>
                    ))}
                </TableBody>
            </Table>
        </CardContent>
    </Card>
);


export default function GlobalWorkPlan() {
    const [plan, setPlan] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const location = useLocation();

    useEffect(() => {
        const params = new URLSearchParams(location.search);
        const projectIds = params.get('projectIds')?.split(',');
        if (projectIds && projectIds.length > 0 && projectIds[0]) {
            runOptimization(projectIds);
        } else {
            setError("没有选择要进行优化的项目。");
            setIsLoading(false);
        }
    }, [location]);

    const runOptimization = async (projectIds) => {
        setIsLoading(true);
        setError(null);
        try {
            const { data } = await optimizeWorkPlan({ projectIds });
            if (data.error) {
                throw new Error(data.error);
            }
            setPlan(data);
        } catch (err) {
            setError(err.message);
        } finally {
            setIsLoading(false);
        }
    };
    
    const ganttData = useMemo(() => {
        if (!plan?.schedule || plan.schedule.length === 0) {
            return [];
        }
        // 按开始日期排序以确保甘特图的基准是正确的
        const sortedSchedule = [...plan.schedule].sort((a, b) => new Date(a.startDate) - new Date(b.startDate));
        const firstStartDate = parseISO(sortedSchedule[0].startDate);
        
        return sortedSchedule.map(task => ({
            ...task,
            // name for Y-axis label
            name: `${task.projectName} - ${task.name}`,
            // gantt bar data: [start_offset, end_offset]
            range: [
                differenceInDays(parseISO(task.startDate), firstStartDate),
                differenceInDays(parseISO(task.endDate), firstStartDate) + 1
            ]
        }));
    }, [plan]);

    const totalTasks = (plan?.schedule?.length || 0) + (plan?.unscheduled?.length || 0);

    return (
        <div className="p-6 bg-gray-50 min-h-screen">
            <div className="max-w-7xl mx-auto">
                <div className="mb-6 flex justify-between items-center">
                    <div>
                        <h1 className="text-3xl font-bold text-gray-900 mb-2 flex items-center gap-3">
                            <GanttChartSquare className="w-8 h-8 text-blue-600" />
                            全局工作规划分析
                        </h1>
                        <p className="text-gray-600">
                            对选定项目进行统筹优化，生成理想的施工排期计划。
                        </p>
                    </div>
                    <Link to={createPageUrl("Projects")}>
                        <Button variant="outline"><ArrowLeft className="w-4 h-4 mr-2" />返回项目管理</Button>
                    </Link>
                </div>

                {isLoading && (
                    <Card>
                        <CardContent className="p-12 text-center">
                            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mx-auto mb-4"></div>
                            <p className="text-lg font-medium text-gray-700">正在进行运筹优化计算...</p>
                            <p className="text-sm text-gray-500">这可能需要一点时间，请稍候。</p>
                        </CardContent>
                    </Card>
                )}

                {error && (
                    <Alert variant="destructive">
                        <AlertTriangle className="h-4 w-4" />
                        <AlertTitle>优化出错</AlertTitle>
                        <AlertDescription>{error}</AlertDescription>
                    </Alert>
                )}

                {plan && !isLoading && (
                    <div className="space-y-6">
                        {totalTasks === 0 ? (
                            <Alert variant="default" className="bg-yellow-50 border-yellow-200">
                                <Info className="h-4 w-4 text-yellow-700" />
                                <AlertTitle className="text-yellow-800">未找到可排期的任务</AlertTitle>
                                <AlertDescription className="text-yellow-700">
                                    在您选择的项目中，没有找到任何处于“已批准”状态的施工方案。请先在【施工方案管理】页面批准相关方案，然后再进行全局优化。
                                </AlertDescription>
                            </Alert>
                        ) : (
                          <>
                            <Card>
                                <CardHeader>
                                    <CardTitle>优化结果概览</CardTitle>
                                </CardHeader>
                                <CardContent className="grid grid-cols-1 md:grid-cols-3 gap-4 text-center">
                                    <div className="p-4 bg-gray-100 rounded-lg">
                                        <ListChecks className="w-8 h-8 mx-auto text-gray-500 mb-2" />
                                        <p className="text-3xl font-bold">{totalTasks}</p>
                                        <p className="text-sm text-gray-600">总任务数</p>
                                    </div>
                                    <div className="p-4 bg-green-50 rounded-lg">
                                        <ThumbsUp className="w-8 h-8 mx-auto text-green-500 mb-2" />
                                        <p className="text-3xl font-bold text-green-700">{plan.schedule.length}</p>
                                        <p className="text-sm text-green-600">已成功排期</p>
                                    </div>
                                    <div className="p-4 bg-red-50 rounded-lg">
                                        <CalendarOff className="w-8 h-8 mx-auto text-red-500 mb-2" />
                                        <p className="text-3xl font-bold text-red-700">{plan.unscheduled.length}</p>
                                        <p className="text-sm text-red-600">无法排期</p>
                                    </div>
                                </CardContent>
                            </Card>

                            {plan.unscheduled?.length > 0 && (
                                <Alert variant="destructive">
                                    <AlertTriangle className="h-4 w-4" />
                                    <AlertTitle>注意：部分任务无法排期</AlertTitle>
                                    <AlertDescription>
                                        以下任务因资源或时间窗口限制，无法在未来一年内找到合适的施工时间：
                                        <ul className="list-disc pl-5 mt-2">
                                            {plan.unscheduled.map(task => (
                                                <li key={task.id}>{task.projectName} - {task.name} ({task.reason})</li>
                                            ))}
                                        </ul>
                                    </AlertDescription>
                                </Alert>
                            )}

                            {plan.schedule.length > 0 && (
                                <Card>
                                    <CardHeader>
                                        <CardTitle>优化后施工甘特图</CardTitle>
                                        <CardDescription>
                                            展示了所有已排期任务的时间分布，X轴代表从第一个任务开始的天数。
                                        </CardDescription>
                                    </CardHeader>
                                    <CardContent className="pr-8">
                                        <ResponsiveContainer width="100%" height={ganttData.length * 50 + 60}>
                                            <BarChart
                                                data={ganttData}
                                                layout="vertical"
                                                margin={{ top: 20, right: 30, left: 200, bottom: 5 }}
                                            >
                                                <CartesianGrid strokeDasharray="3 3" />
                                                <XAxis type="number" unit="天" />
                                                <YAxis dataKey="name" type="category" width={200} tick={{ fontSize: 12 }} />
                                                <Tooltip content={<CustomTooltip />} />
                                                <Bar dataKey="range" fill="#3b82f6" />
                                            </BarChart>
                                        </ResponsiveContainer>
                                    </CardContent>
                                </Card>
                            )}
                            
                            {plan.schedule.length > 0 && 
                                <TaskList tasks={plan.schedule} title="已排期任务清单" icon={<CheckCircle className="text-green-500" />} />
                            }
                          </>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
}